﻿using System;
using System.Collections.Generic;
using BestHTTP;
using HyxFrame.Core;
using UnityEngine;

public class ImageCacheManager
{
    private readonly Dictionary<string, Texture2D> cache = new Dictionary<string, Texture2D>();
    private readonly Queue<string> cacheOrder = new Queue<string>();
    private int maxCacheCount = 50; // 默认最大缓存数，可根据需要调整

    public void SetMaxCacheCount(int count)
    {
        maxCacheCount = count;
        CleanCacheIfNeeded();
    }

    public Texture2D GetImageFromCache(string url)
    {
        if (cache.TryGetValue(url, out var texture))
            return texture;
        return null;
    }

    public void AddImageToCache(string url, Texture2D texture)
    {
        if (!cache.ContainsKey(url) && texture != null)
        {
            cache[url] = texture;
            cacheOrder.Enqueue(url);

            CleanCacheIfNeeded();
        }
    }

    private void CleanCacheIfNeeded()
    {
        while (cache.Count > maxCacheCount)
        {
            var oldestUrl = cacheOrder.Dequeue();
            cache.Remove(oldestUrl);
        }
    }
}

public class ImageDownloader : Singleton<ImageDownloader>
{
    private ImageCacheManager imageCache = new ImageCacheManager();

    protected override void Init() { }

    /// <summary>
    /// 下载图片并返回 Texture2D
    /// </summary>
    public void DownloadImage(string url, Action<Texture2D> onFinish)
    {
        var cachedTexture = imageCache.GetImageFromCache(url);
        if (cachedTexture != null)
        {
            onFinish?.Invoke(cachedTexture);
            return;
        }

        new HTTPRequest(new Uri(url), (request, response) =>
        {
            if (response.IsSuccess)
            {
                var texture = response.DataAsTexture2D;
                imageCache.AddImageToCache(url, texture);
                onFinish?.Invoke(texture);
            }
            else
            {
                onFinish?.Invoke(null);
            }
        }).Send();
    }

    /// <summary>
    /// 下载图片并返回 Sprite
    /// </summary>
    public void DownloadImageAsSprite(string url, Action<Sprite> onFinish)
    {
        DownloadImage(url, (texture) =>
        {
            if (texture != null)
            {
                Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
                onFinish?.Invoke(sprite);
            }
            else
            {
                onFinish?.Invoke(null);
            }
        });
    }

    /// <summary>
    /// 设置最大缓存数
    /// </summary>
    /// <param name="count"></param>
    public void SetMaxCacheCount(int count)
    {
        imageCache.SetMaxCacheCount(count);
    }
}